'''
Авторские права принадлежат Алифатову Дмитрию Сергеевичу <dmitry@alifatov.ru>

Вы можете использовать данное Программное обеспечение на любом количестве компьютеров.

Не разрешается распространять Программное обеспечение, извлекать его компоненты и создавать производные работы на его основе.
'''
import astra
import networking
import npyscreen
import ipaddress
import validate
import curses
import os
from astra import truncate_string
from astra import system_call
from astra import split_string

def speed_to_string(speed):
    if speed == 10:
        return "10 Mbps"
    elif speed == 100:
        return "100 Mbps"
    elif speed == 1000:
        return "1 Gbps"
    elif speed == 10000:
        return "10 Gbps"
    elif speed == 25000:
        return "25 Gbps"
    elif speed == 100000:
        return "100 Gbps"
    return "-"

class ConfigureIP(npyscreen.ActionForm):
    def __init__(self, ifname):
        super().__init__()
        self.interface = network.get_interface_object_by_name(ifname)
        self.name = f"{self.interface.name} - конфигурация IP"

        self.widget_mtu = self.add(npyscreen.TitleText, begin_entry_at=16, name="MTU:", value=f"{self.interface.mtu}")
        #self.widget_hwaddress = self.add(npyscreen.TitleText, begin_entry_at=16, name="MAC-адрес:", value=f"{self.interface.hwaddress}")
        self.nextrely += 1

        if self.interface.inet == "dhcp":
            default_value = [1]
        elif self.interface.inet == "static":
            default_value = [2]
        else:
            default_value = [0] # manual

        self.widget_inet = self.add(npyscreen.TitleSelectOne, begin_entry_at=16, max_height=4, value=default_value, name="IP",
                             values=["Нет(manual)", "DHCP", "Static"], scroll_exit=True)
        self.widget_ip_mask = self.add(npyscreen.TitleText, begin_entry_at=16, name="IP-адрес:",
                                value=f"{self.interface.ip}/{self.interface.netmask}", hidden=True)
        self.widget_gateway = self.add(npyscreen.TitleText, begin_entry_at=16, name="Шлюз:", value=f"{self.interface.gateway}",
                                hidden=True)
        self.widget_dns1 = self.add(npyscreen.TitleText, begin_entry_at=24, name="Первый DNS-сервер:", value=f"{self.interface.dns1}", hidden=True)
        self.widget_dns2 = self.add(npyscreen.TitleText, begin_entry_at=24, name="Второй DNS-сервер:", value=f"{self.interface.dns2}", hidden=True)






    def adjust_widgets(self):
        # если режим конфигурации Static (2) то, показать поля ввода IP-адреса
        if self.widget_inet.value == [2]:
            self.widget_ip_mask.hidden = False
            self.widget_ip_mask.editable = True
            self.widget_gateway.hidden = False
            self.widget_gateway.editable = True
            self.widget_dns1.hidden = False
            self.widget_dns1.editable = True
            self.widget_dns2.hidden = False
            self.widget_dns2.editable = True
        else:
            self.widget_ip_mask.hidden = True
            self.widget_ip_mask.editable = False
            self.widget_gateway.hidden = True
            self.widget_gateway.editable = False
            self.widget_dns1.hidden = True
            self.widget_dns1.editable = False
            self.widget_dns2.hidden = True
            self.widget_dns2.editable = False
        self.display()

    def on_ok(self):
        if self.widget_inet.value == [0]:
            self.interface.inet = 'manual'
        elif self.widget_inet.value == [1]:
            self.interface.inet = 'dhcp'
        else:
            self.interface.inet = 'static'
            # проверяемя валидность IP-адреса
            try:
                self.interface.ip = ipaddress.ip_interface(self.widget_ip_mask.value).ip
                self.interface.netmask = str(ipaddress.ip_interface(self.widget_ip_mask.value).network).split('/')[1]
            except:
                Message = "Проверьте правильность введения IP-адреса"
                npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False, editw=0)
                self.editing = True
                return
            if str(self.interface.ip) == str(ipaddress.ip_interface(self.widget_ip_mask.value).network).split('/')[0]:
                Message = "Проверьте правильность введения IP-адреса"
                npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False, editw=0)
                self.editing = True
                return
            # проверяем валидность шлюза по умолчанию
            if self.widget_gateway.value != "":
                try:
                    self.interface.gateway = ipaddress.ip_interface(self.widget_gateway.value).ip
                    if not networking.verify_ip_subnet(self.interface.gateway, ipaddress.ip_interface(self.widget_ip_mask.value).network):
                        Message = f"Проверьте правильность введения адреса шлюза по умолчанию."
                        npyscreen.notify_confirm(Message, title="Message YES", form_color='STANDOUT', wrap=True,
                                                 wide=False, editw=0)
                        self.editing = True
                        return
                    network.main_ip = self.interface.ip
                except:
                    Message = "Проверьте правильность введения адреса шлюза по умолчанию"
                    npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False,
                                             editw=0)
                    self.editing = True
                    return

        # Проверяем нужно ли задавать DNS
        if self.widget_dns1.value != "":
            try:
                self.interface.dns1 = ipaddress.ip_interface(self.widget_dns1.value).ip
            except:
                Message = "Проверьте правильность введения адреса первого DNS-сервера"
                npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False,
                                         editw=0)
                self.editing = True
                return
        else:
            self.interface.dns1 = ""
            self.interface.dns2 = ""
        if self.widget_dns2.value != "":
            try:
                self.interface.dns2 = ipaddress.ip_interface(self.widget_dns2.value).ip
                if self.widget_dns1.value == "":
                    Message = "Укажите адрес первого DNS-сервера"
                    npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False,
                                             editw=0)
                    self.editing = True
                    return
            except:
                Message = "Проверьте правильность введения адреса второго DNS-сервера"
                npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False,
                                         editw=0)
                self.editing = True
                return
        else:
            self.interface.dns1 = ""


        # Проверяем нужно ли менять MTU
        if not validate.mtu(str(self.widget_mtu.value)):
            Message = "Проверьте правильность MTU"
            npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False, editw=0)
            self.editing = True
            return
        self.interface.mtu = str(self.widget_mtu.value)

        # сохраняем измененные параметры IP
        if self.interface.type == "ethernet":
            for nic in network.nics:
                if nic.name == self.interface.name:
                    nic = self.interface
        elif self.interface.type == "bond":
            for bond in network.bonds:
                if bond.name == self.interface.name:
                    bond = self.interface
        elif self.interface.type == "bridge":
            for bridge in network.bridges:
                if bridge.name == self.interface.name:
                    bridge = self.interface
        elif self.interface.type == "vlan":
            for vlan in network.vlans:
                if vlan.name == self.interface.name:
                    vlan = self.interface


    def on_cancel(self):
        pass

class ConfigureBond(npyscreen.FormMultiPageAction):

    possible_modes = ["balance-rr", "active-backup", "balance-xor", "broadcast", "802.3ad", "balance-tlb",
                      "balance-alb"]
    possible_xmit_hash_policy = ["layer2", "layer3+4", "layer2+3", "encap2+3", "encap3+4"]

    def __init__(self, ifname=""):
        super().__init__()
        if ifname == "":
            for i in range(0,256):
                ifname = "bond" + str(i)
                if network.get_interface_object_by_name(ifname) == None:
                    self.interface = networking.Bond(name=ifname)
                    # bond_min_links = 2,  # Denotes the minimum number of available links before turning on carrier.
                    self.widget_bond_name = self.add_widget_intelligent(npyscreen.TitleText,
                                                                                          begin_entry_at=40,
                                                                                          value=str(
                                                                                              self.interface.name),
                                                                                          name="Имя объединенного интерфейса")
                    break
        else:
            self.interface = network.get_interface_object_by_name(ifname)
        self.nextrely += 1

        nextrely = self.nextrely

        self.add_handlers({"^X": self.h_bond_extended_form, curses.KEY_F1: self.h_bond_form_help,})
        self.footer = "Ctrl+X: Раширенные параметры"
        # bond-members list of interfaces. Denotes the physical member interfaces to form this LAG. For compatiblity to ifupdown1 and ifupdown2 slaves as well as bond-slaves are an alias for this option. This option is required.
        self.members = []
        self.possible_members = []
        self.already_members = []
        for nic in network.nics:
            if nic.master in ["", ifname]:
                self.possible_members.append(nic.name)
                if nic.master == ifname:
                    self.already_members.append(len(self.possible_members) - 1)
        if self.possible_members == [] and self.alredy_members == []:
            self.add_widget_intelligent(npyscreen.FixedText, begin_entry_at=4,
                                        value="Отсутcвуют свободные интефейсы для конфигурации bond")
            return
        self.widget_members = self.add_widget_intelligent(npyscreen.TitleMultiSelect,
                                                          name="Интерфейсы для объединения:",
                                                          values=self.possible_members, value=self.already_members,
                                                          begin_entry_at=1, relx=2, rely=nextrely, max_height=self.max_y - 13,
                                                          max_width=int(self.max_x / 3) - 3,
                                                          scroll_exit=True)
        for index in self.widget_members.value:
            self.members.append(self.possible_members[index])

        # bond_mode = "balance-rr",  # bond-mode mode. Denotes the mode for this LAG. The mode can be given as string or as numerical value. Valid values are balance-rr (0), active-backup (1), balance-xor (2), broadcast (3), 802.3ad (4), balance-tlb (5), balance-alb (6). The default is balance-rr
        for index in range(0, 6):
            if self.interface.bond_mode == self.possible_modes[index] or str(self.interface.bond_mode) == str(
                    self.possible_modes[index]):
                selected_mode = index
                break
        self.widget_mode = self.add_widget_intelligent(npyscreen.TitleSelectOne, name="Режим балансировки:",
                                                       values=self.possible_modes, value=selected_mode,
                                                       begin_entry_at=1, relx=int(self.max_x / 3), rely=nextrely,
                                                       max_height=self.max_y - 13, max_width=int(self.max_x / 3) - 3,
                                                       scroll_exit=True)
        self.mode = self.possible_modes[self.widget_mode.value]

        # bond-xmit-hash-policy policy. Denotes the hash policy/algorithm used to distribute packets across the physical links. This only applies for modes balance-alb, balance-tlb, balance-xor, and 802.3ad. The policy can be given as string or as numerical value. Valid values are layer2 (0), layer3+4 (1), layer2+3 (2), encap2+3 (3), and encap3+4 (4). The default is layer2.
        for index in range(0, 4):
            if self.interface.bond_xmit_hash_policy == self.possible_xmit_hash_policy[index] or str(
                    self.interface.bond_xmit_hash_policy) == str(self.possible_xmit_hash_policy[index]):
                selected_xmit_hash_policy = [index]
                break
        if self.mode in ["balance-alb", "balance-tlb", "balance-xor", "802.3ad"]:
            is_widget_xmit_hash_policy_hidden = False
        else:
            is_widget_xmit_hash_policy_hidden = True
        self.widget_xmit_hash_policy = self.add_widget_intelligent(npyscreen.TitleSelectOne, name="Алгоритм "
                                                                                                  "хэширования:",
                                                                   values=self.possible_xmit_hash_policy,
                                                                   value=selected_xmit_hash_policy,
                                                                   begin_entry_at=1,
                                                                   relx=int(self.max_x / 3 * 2), rely=nextrely,
                                                                   max_height=self.max_y - 13,
                                                                   max_width=int(self.max_x / 3) - 3,
                                                                   hidden=is_widget_xmit_hash_policy_hidden,
                                                                   scroll_exit=True)
        self.xmit_hash_policy = self.possible_xmit_hash_policy[self.widget_xmit_hash_policy.value[0]]

    def adjust_widgets(self):
        if self.possible_modes[self.widget_mode.value[0]] in ["balance-alb", "balance-tlb", "balance-xor", "802.3ad"]:
            self.widget_xmit_hash_policy.hidden = False
        else:
            self.widget_xmit_hash_policy.hidden = True

        self.display()

    def on_ok(self):

        # Основные параметры
        if network.get_interface_object_by_name(self.interface.name) == None:
            self.interface.name = self.widget_bond_name.value
        self.interface.bond_members = []
        for member_id in self.widget_members.value:
            self.interface.bond_members.append(self.possible_members[member_id])

        self.interface.bond_mode = self.possible_modes[self.widget_mode.value[0]]
        self.interface.bond_xmit_hash_policy = self.possible_xmit_hash_policy[self.widget_xmit_hash_policy.value[0]]


        #Сохраняем параметры
        if network.get_interface_object_by_name(self.interface.name) == None:
            if self.interface.bond_members == []:
                return
            network.bonds.append(self.interface)
        else:
            for bond in network.bonds:
                if bond.name == self.interface.name:
                    if self.interface.bond_members == []:
                        network.bonds.remove(bond)
                    else:
                        bond = self.interface
        for nic in network.nics:
            if nic.master == self.interface.name:
                nic.master = ""
                nic.bond_member = False
            if nic.name in self.interface.bond_members:
                nic.master = self.interface.name
                nic.bond_member = True
                nic.inet = "manual"
                nic.ip = ""
                nic.netmask = ""
                nic.gateway = ""


    def on_cancel(self):
        pass
        # self.parentApp.change_form("ConfigureNetwork")

    def h_bond_extended_form(self, *args, **keywords):
        extended_form = npyscreen.FormMultiPageAction()
        extended_form.add_handlers({curses.KEY_F1: self.h_bond_extended_form_help, })
        extended_form.footer = "F1 Помощь"
        max_width = int(extended_form.max_x ) - 25
        begin_entry_at = max_width - 25
        # Расширенные параметры
        extended_form.add_widget_intelligent(npyscreen.FixedText, value="Расширенные параметры:")

        # bond_min_links = 2,  # Denotes the minimum number of available links before turning on carrier.
        extended_form.widget_min_links = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                            value=str(self.interface.bond_min_links),
                                                            name="min-links", max_width=max_width)

        # bond_miimon = 0,  # Denotes the MII link monitoring frequency in milliseconds. This determines how often the link state of each slave is inspected for link failures. A value of zero disables MII link monitoring. The default is 0.
        extended_form.widget_miimon = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                         value=str(self.interface.bond_miimon),
                                                         name="miimon", max_width=max_width)

        # bond_use_carrier = True,  # Denotes wether miimon uses MII or ethtool ioctls vs. the netif_carrier_ok() call to determine member link status. A value of 1 enables the use of netif_carrier_ok(), a value of 0 will use the deprecated MII / ETHTOOL ioctls. The default is 1.
        extended_form.widget_use_carrier = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                              value=str(self.interface.bond_use_carrier),
                                                              name="use-carrier", max_width=max_width)

        # bond_updelay = 0,  # Denotes the delay in milliseconds before considering link up, in milliseconds. The default is 0.
        extended_form.widget_updelay = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                          value=str(self.interface.bond_updelay),
                                                          name="updelay", max_width=max_width)

        # bond_downdelay = 0,  # Denotes the delay in milliseconds before considering link down, in milliseconds. The default is 0.
        extended_form.widget_downdelay = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                            value=str(self.interface.bond_downdelay),
                                                            name="downdelay", max_width=max_width)

        # bond_all_slaves_active = False,  # Denotes wether duplicate frames (received on inactive ports) should be dropped (0) or delivered (1). The default is 0.
        extended_form.widget_all_slaves_active = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                                    value=str(self.interface.bond_all_slaves_active),
                                                                    name="all-slaves-active", max_width=max_width)

        # bond_packets_per_slave = 1,  # Denotes the number of packets to transmit through a member before moving to the next one. When set to 0 then a slave is chosen at random. The valid range is 0 - 65535; the default value is 1. This option has effect only in balance-rr mode.
        extended_form.widget_packets_per_slave = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                                    value=str(self.interface.bond_packets_per_slave),
                                                                    name="packets-per-slave", max_width=max_width)

        # bond_lp_interval = 1,  # Denotes the interval in seconds between sending learning packets to each members peer switch. The valid range is 1 - 0x7fffffff; the default value is 1. This option has effect only in modes balance-tlb and balance-alb.
        extended_form.widget_lp_interval = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                              value=str(self.interface.bond_lp_interval),
                                                              name="lp-interval", max_width=max_width)

        # bond_resend_igmp = 1,  # Denotes the number of IGMP membership reports to send after a link failover happend. The valid range is 0 - 255; a value of 0 prevents the IGMP membership report from being issued in response to the failover event. The default is 1. This option is useful for bonding modes balance-rr, active-backup balance-tlb and balance-alb, in which a failover can switch the IGMP traffic from one slave to another.
        extended_form.widget_resend_igmp = extended_form.add_widget_intelligent(npyscreen.TitleText, begin_entry_at=begin_entry_at,
                                                              value=str(self.interface.bond_resend_igmp),
                                                              name="resend-igmp", max_width=max_width)

        # ARP-RELATED OPTIONS -    The following options configure ARP link monitoring. The ARP monitor works by periodically checking the slave devices to determine whether they have sent or received traffic recently. Regular traffic is generated via ARP probes issued for the addresses specified by the bond-arp-ip-target option.
        extended_form.nextrely += 1
        extended_form.add_widget_intelligent(npyscreen.FixedText, value="ARP-RELATED OPTIONS:")

        # bond_arp_interval = 0,  # Denotes the frequency in milliseconds to send ARP probes.
        extended_form.widget_arp_interval = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                begin_entry_at=begin_entry_at,
                                                                                value=str(
                                                                                    self.interface.bond_arp_interval),
                                                                                name="arp-interval",
                                                                                max_width=max_width)

        # bond_arp_ip_target = None,  # Denotes the IP addresses to use as ARP monitoring peers when bond-arp-interval is > 0.
        extended_form.widget_arp_ip_target = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                 begin_entry_at=begin_entry_at,
                                                                                 value=str(
                                                                                     self.interface.bond_arp_ip_target),
                                                                                 name="arp-ip-target",
                                                                                 max_width=max_width)

        # bond_arp_validate = "none",  # Specifies whether or not ARP probes and replies should be validated in any mode that supports arp monitoring, or whether non-ARP traffic should be filtered (disregarded) for link monitoring purposes. Valid values are none (0), active (1), backup (2), all (3), filter (4), filter_active (5), and filter_backup (6). The default is none.
        extended_form.widget_arp_validate = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                  begin_entry_at=begin_entry_at,
                                                                                  value=str(
                                                                                      self.interface.bond_arp_validate),
                                                                                  name="arp-validate",
                                                                                  max_width=max_width)

        # bond_arp_all_targets = "any"  # Denotes the number of bond-arp-ip-targets that have to be reachable to consider the member interface to be up. Valid options are any (0) and all (1). The default is any.
        extended_form.widget_arp_all_targets = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                 begin_entry_at=begin_entry_at,
                                                                                 value=str(
                                                                                     self.interface.bond_arp_all_targets),
                                                                                 name="arp-all-targets",
                                                                                 max_width=max_width)


        # ACTIVE/BACKUP-RELATED OPTIONS - The following options are only valid in active/passive setups.

        if self.possible_modes[self.widget_mode.value[0]] in ["active-backup", "balance-tlb", "balance-alb"]:
            extended_form.nextrely += 1
            extended_form.add_widget_intelligent(npyscreen.FixedText, value="ACTIVE/BACKUP-RELATED OPTIONS:")

            # bond_primary = None,  # Denotes the primary member interface The specified device will always be the active slave while it is available. The primary option is only valid for active-backup, balance-tlb and balance-alb mode.
            extended_form.widget_primary = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                        begin_entry_at=begin_entry_at,
                                                                                        value=str(
                                                                                            self.interface.bond_primary),
                                                                                        name="primary",
                                                                                        max_width=max_width)

            # bond_primary_reselect = "always",  # Denotes the reselection policy for the primary member interface. Valid values are always (0), better (1), and failure (2). The default is always.
            extended_form.widget_primary_reselect = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                        begin_entry_at=begin_entry_at,
                                                                                        value=str(
                                                                                            self.interface.bond_primary_reselect),
                                                                                        name="primary-reselect",
                                                                                        max_width=max_width)

            # bond_fail_over_mac = "none",  # Denotes whether active-backup mode should set all member interfaces to the same MAC address at enslavement (the traditional behavior), or, when enabled, perform special handling of the bond's MAC address in accordance with the selected policy. Valid values are none (0), active (1), follow (2). The default is none.
            extended_form.widget_fail_over_mac = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                        begin_entry_at=begin_entry_at,
                                                                                        value=str(
                                                                                            self.interface.bond_fail_over_mac),
                                                                                        name="fail-over-mac",
                                                                                        max_width=max_width)

            # bond_num_grat_arp = 1,  # Denotes the number of peer notifications (gratuitous ARPs and unsolicited IPv6 Neighbor Advertisements) to be issued after a failover event. The valid range is 0 - 255; the default is 1.
            extended_form.widget_num_grat_arp = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                      begin_entry_at=begin_entry_at,
                                                                                      value=str(
                                                                                          self.interface.bond_num_grat_arp),
                                                                                      name="num-grat-arp",
                                                                                      max_width=max_width)

            # bond_peer_notif_delay = 0,  # Denotes the interval in milliseconds, between each peer notification (gratuitous ARP and unsolicited IPv6 Neighbor Advertisement) issued after a failover event. The default is 0 which means to match the value of the link monitor interval.
            extended_form.widget_peer_notif_delay = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                     begin_entry_at=begin_entry_at,
                                                                                     value=str(
                                                                                         self.interface.bond_peer_notif_delay),
                                                                                     name="peer-notif-delay",
                                                                                     max_width=max_width)

        # LACP-RELATED OPTIONS - The following options are only valid in LACP (802.3ad) mode.
        if self.possible_modes[self.widget_mode.value[0]] in ["802.3ad"]:
            extended_form.nextrely += 1
            extended_form.add_widget_intelligent(npyscreen.FixedText, value="LACP-RELATED OPTIONS:")
            # bond_lacp_rate = "slow",  # Denotes the rate of LACPDU requested from the peer. The rate can be given as string or as numerical value. Valid values are slow (0) and fast (1). The default is slow.
            extended_form.widget_lacp_rate = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                      begin_entry_at=begin_entry_at,
                                                                                      value=str(
                                                                                          self.interface.bond_lacp_rate),
                                                                                      name="lacp-rate",
                                                                                      max_width=max_width)

            # bond_ad_select = "stable",  # Denotes the 802.3ad aggregation selection logic. The mode can be given as string or as numerical value. Valid values are stable (0), bandwidth (1) and cound (2). The default is stable.
            extended_form.widget_ad_select = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                      begin_entry_at=begin_entry_at,
                                                                                      value=str(
                                                                                          self.interface.bond_ad_select),
                                                                                      name="ad_select",
                                                                                      max_width=max_width)

            # bond_ad_actor_sys_prio = 65535,  # Denotes the LACP system priority. The allowed range is 1 - 65535. The default value is 65535.
            extended_form.widget_ad_actor_sys_prio = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                              begin_entry_at=begin_entry_at,
                                                                                              value=str(
                                                                                                  self.interface.bond_ad_actor_sys_prio),
                                                                                              name="ad-actor-sys-prio",
                                                                                              max_width=max_width)

            # bond_ad_user_port_key = 0,  # Denotes the upper 10 bits of the port-key. he values can be from 0 - 1023. The default is 0.

            extended_form.widget_ad_user_port_key = extended_form.add_widget_intelligent(npyscreen.TitleText,
                                                                                             begin_entry_at=begin_entry_at,
                                                                                             value=str(
                                                                                                 self.interface.bond_ad_user_port_key),
                                                                                             name="ad-user-port-key",
                                                                                             max_width=max_width)

        extended_form.edit()
        if extended_form: #если нажали ОК
            #передаем расширенные параметры в основную форму настройки bond
            self.interface.bond_min_links = extended_form.widget_min_links.value
            self.interface.bond_miimon = extended_form.widget_miimon.value
            self.interface.bond_updelay = extended_form.widget_updelay.value
            self.interface.bond_downdelay = extended_form.widget_downdelay.value
            self.interface.bond_all_slaves_active = extended_form.widget_all_slaves_active.value
            self.interface.bond_packets_per_slave = extended_form.widget_packets_per_slave.value
            self.interface.bond_lp_interval = extended_form.widget_lp_interval.value
            self.interface.bond_resend_igmp = extended_form.widget_resend_igmp.value

            # LACP-RELATED OPTIONS - The following options are only valid in LACP (802.3ad) mode.
            if self.possible_modes[self.widget_mode.value[0]] in ["802.3ad"]:
                self.interface.bond_lacp_rate = extended_form.widget_lacp_rate.value
                self.interface.bond_ad_select = extended_form.widget_ad_select.value
                self.interface.bond_ad_actor_sys_prio = extended_form.widget_ad_actor_sys_prio.value
                self.interface.bond_ad_user_port_key = extended_form.widget_ad_user_port_key
            # ACTIVE/BACKUP-RELATED OPTIONS - The following options are only valid in active/passive setups.
            if self.possible_modes[self.widget_mode.value[0]] in ["active-backup", "balance-tlb", "balance-alb"]:
                self.interface.bond_primary = extended_form.widget_primary.value
                self.interface.bond_primary_reselect = extended_form.widget_primary_reselect.value
                self.interface.bond_fail_over_mac = extended_form.widget_fail_over_mac.value
                self.interface.bond_num_grat_arp = extended_form.widget_num_grat_arp.value
                self.interface.bond_peer_notif_delay = extended_form.widget_peer_notif_delay.value
            # ARP-RELATED OPTIONS -    The following options configure ARP link monitoring. The ARP monitor works by periodically checking the slave devices to determine whether they have sent or received traffic recently. Regular traffic is generated via ARP probes issued for the addresses specified by the bond-arp-ip-target option.
            self.interface.bond_arp_interval = extended_form.widget_arp_interval.value
            self.interface.bond_arp_ip_target = extended_form.widget_arp_ip_target.value
            self.interface.bond_arp_validate = extended_form.widget_arp_validate.value
            self.interface.bond_arp_all_targets = extended_form.widget_arp_all_targets.value

    def h_bond_form_help(self, *args, **keywords):
        bond_form_help = npyscreen.FormMultiPageAction(name=f"Объединение интерфейсов")
        #self.add_handlers({"^H": self.extended_menu_help, })
        #extended_form.footer = "Ctrl+H Помощь"
        # Расширенные параметры
        try:
            f = open('bond_form_help.txt', 'r')
            bond_form_help_text = f.read()
        finally:
            f.close()
        bond_form_help.add_widget_intelligent(npyscreen.FixedText, value=bond_form_help_text)
        bond_form_help.edit()

    def h_bond_extended_form_help(self, *args, **keywords):
        bond_extended_form_help = npyscreen.FormMultiPageAction(name=f"Объединение интерфейсов, расширенные параметры")
        #self.add_handlers({"^H": self.extended_menu_help, })
        #extended_form.footer = "Ctrl+H Помощь"
        # Расширенные параметры
        bond_extended_form_help.add_widget_intelligent(npyscreen.FixedText, name="", value="saf asf asfdas fasdf asdf")

        bond_extended_form_help.edit()

class ConfigureBridge(npyscreen.FormMultiPageAction):
    def __init__(self, ifname=""):
        super().__init__()
        if ifname == "":
            for i in range(0,256):
                ifname = "br" + str(i)
                if network.get_interface_object_by_name(ifname) == None:
                    self.interface = networking.Bridge(name=ifname)
                    self.widget_bridge_name = self.add_widget_intelligent(npyscreen.TitleText,
                                                                                          begin_entry_at=40,
                                                                                          value=str(
                                                                                              self.interface.name),
                                                                                          name="Имя моста")
                    break
        else:
            self.interface = network.get_interface_object_by_name(ifname)
        self.nextrely += 1

        nextrely = self.nextrely

        #self.add_handlers({"^X": self.h_bridge_extended_form, curses.KEY_F1: self.h_bridge_form_help,})
        #self.footer = "Ctrl+X: Раширенные параметры, F1: Помощь"

        # Bridge members
        self.members = []
        self.possible_members = []
        self.already_members = []
        for nic in network.nics:
            if nic.master in ["", ifname] and nic.vlans_count == 0:
                self.possible_members.append(nic.name)
                if nic.master == ifname:
                    self.already_members.append(len(self.possible_members) - 1)
        for bond in network.bonds:
            if bond.master in ["", ifname] and bond.vlans_count == 0:
                self.possible_members.append(bond.name)
                if bond.master == ifname:
                    self.already_members.append(len(self.possible_members) - 1)
        for vlan in network.vlans:
            if vlan.master in ["", ifname]:
                self.possible_members.append(vlan.name)
                if vlan.master == ifname:
                    self.already_members.append(len(self.possible_members) - 1)

        if self.possible_members == [] and self.alredy_members == []:
            self.add_widget_intelligent(npyscreen.FixedText, begin_entry_at=4,
                                        value="Отсутcвуют свободные интефейсы для конфигурации bond")
            return
        self.widget_bridge_members = self.add_widget_intelligent(npyscreen.TitleMultiSelect,
                                                          name="Интерфейсы для настройки моста:",
                                                          values=self.possible_members, value=self.already_members,
                                                          begin_entry_at=1, relx=2, rely=nextrely, max_height=self.max_y - 13,
                                                          max_width=int(self.max_x / 3) - 3, scroll_exit=True)
        for index in self.widget_bridge_members.value:
            self.members.append(self.possible_members[index])


    def adjust_widgets(self):
        self.display()

    def on_ok(self):

        # Основные параметры
        if network.get_interface_object_by_name(self.interface.name) == None:
            self.interface.name = self.widget_bridge_name.value
        self.interface.bridge_ports = []
        for member_id in self.widget_bridge_members.value:
            self.interface.bridge_ports.append(self.possible_members[member_id])


        #Сохраняем параметры
        if network.get_interface_object_by_name(self.interface.name) == None:
            if self.interface.bridge_ports == []:
                return
            network.bridges.append(self.interface)
        else:
            for bridge in network.bridges:
                if bridge.name == self.interface.name:
                    if self.interface.bridge_ports == []:
                        network.bridges.remove(bridge)
                    else:
                        bridge = self.interface
        for nic in network.nics:
            if nic.master == self.interface.name:
                nic.master = ""
                nic.bridge_member = False
            if nic.name in self.interface.bridge_ports:
                nic.master = self.interface.name
                nic.bridge_member = True
                nic.inet = "manual"
                nic.ip = ""
                nic.netmask = ""
                nic.gateway = ""
        for bond in network.bonds:
            if bond.master == self.interface.name:
                bond.master = ""
                bond.bridge_member = False
            if bond.name in self.interface.bridge_ports:
                bond.master = self.interface.name
                bond.bridge_member = True
                bond.inet = "manual"
                bond.ip = ""
                bond.netmask = ""
                bond.gateway = ""
        for vlan in network.vlans:
            if vlan.master == self.interface.name:
                vlan.master = ""
                vlan.bridge_member = False
            if vlan.name in self.interface.bridge_ports:
                vlan.master = self.interface.name
                vlan.bridge_member = True
                vlan.inet = "manual"
                vlan.ip = ""
                vlan.netmask = ""
                vlan.gateway = ""

    def on_cancel(self):
        pass

    def h_bridge_extended_form(self, *args, **keywords):
        pass

    def h_bridge_form_help(self, *args, **keywords):
        pass

    def h_bridge_extended_form_help(self, *args, **keywords):
        pass

class ConfigureVlan(npyscreen.ActionPopup):
    def __init__(self, ifname):
        super().__init__()
        self.ifname = ifname
        self.widget_vlan_id = self.add_widget(npyscreen.TitleText,
                                                            begin_entry_at=40,
                                                            value="0",
                                                            name="VLAN ID")

    def on_ok(self):
        for vlan in network.vlans:
            if vlan.vlan_raw_device == self.ifname and vlan.vlan_id == self.widget_vlan_id.value:
                Message = f"VLAN {vlan.vlan_id} уже настроен на этом интерфейсе"
                npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False, editw=0)
                return
        self.vlan = networking.Vlan(f"{self.ifname}.{self.widget_vlan_id.value}")
        network.vlans.append(self.vlan)
        network.get_interface_object_by_name(self.vlan.vlan_raw_device).vlans_count =+ 1


    def on_cancel(self):
        pass

class Form_Configure_Network(npyscreen.FormMultiPageAction):
    button_press_function = None
    def create(self):
        global network
        network = networking.Network()
        self.draw_widgets()

    def draw_widgets(self):
        self.form_buttons = []  # делаем все строчки с сетевыми интерфесами кнопками и добавляем их в список

        header = "Физические сетевые интерфейсы"
        header = "[" + truncate_string(header, 81) + "]"
        self.add_widget_intelligent(npyscreen.TitleFixedText, name=" ", begin_entry_at=4, value=header, editable=False)
        # перечисление физических сетевых интерфесов
        header = ""
        header += 'Name' + (17 - len('Name')) * ' '
        header += 'Speed' + (10 - len('Speed')) * ' '
        header += 'MAC' + (21 - len('MAC')) * ' '
        header += 'IP' + (21 - len('IP')) * ' '
        header += 'Inet' + (8 - len('Inet')) * ' '
        header += 'Member' + (21 - len('Member')) * ' '

        self.add_widget_intelligent(npyscreen.TitleFixedText, name=" ", begin_entry_at=4, value=header, editable=False)
        for nic in network.nics:
            line = ""
            if nic.ip != "":
                ip_address = str(nic.ip) + '/' + str(nic.netmask)
            else:
                ip_address = "-"
            if nic.up:
                status = "Up"
            else:
                status = "Down"
            if nic.master != "":
                member = nic.master
            else:
                member = "-"
            line += truncate_string(nic.name, 17)
            line += truncate_string(speed_to_string(nic.link_speed), 10)
            line += truncate_string(nic.hwaddress, 21)
            line += truncate_string(ip_address, 21)
            line += truncate_string(nic.inet, 8)
            line += truncate_string(member, 21)
            self.form_buttons.append(
                self.add_widget_intelligent(npyscreen.ButtonPress, relx=4, name=line, parameters=str(nic.name),
                                            when_pressed_function=self.buttonPress))

            for vlan in network.vlans:
                if vlan.vlan_raw_device == nic.name:
                    line = " ‣"
                    if vlan.ip != "":
                        ip_address = str(vlan.ip) + '/' + str(vlan.netmask)
                    else:
                        ip_address = "-"
                    member = ""
                    line += truncate_string(vlan.name, 15)
                    line += truncate_string(" ", 10)
                    line += truncate_string(" ", 21)
                    line += truncate_string(ip_address, 21)
                    line += truncate_string(vlan.inet, 8)
                    line += truncate_string(member, 21)
                    self.form_buttons.append(
                        self.add_widget_intelligent(npyscreen.ButtonPress, relx=4, name=line, parameters=str(vlan.name),
                                                    when_pressed_function=self.buttonPress))

        self.nextrely += 1

        # перечисление портов bond
        header = "Объединение портов"
        header = "[" + truncate_string(header, 81) + "]"
        self.add_widget_intelligent(npyscreen.TitleFixedText, name=" ", begin_entry_at=4, value=header, editable=False)
        if network.bonds != []:
            header = ""
            header += 'Name' + (17 - len('Name')) * ' '
            header += 'Mode' + (15 - len('Mode')) * ' '
            #header += 'MAC' + (21 - len('MAC')) * ' '
            header += 'IP' + (21 - len('IP')) * ' '
            header += 'Inet' + (8 - len('Inet')) * ' '
            header += 'Members' + (32 - len('Members')) * ' '

            self.add_widget_intelligent(npyscreen.TitleFixedText, name=" ", begin_entry_at=4, value=header, editable=False)

            for bond in network.bonds:
                line = ""
                if bond.ip != "":
                    ip_address = str(bond.ip) + '/' + str(bond.netmask)
                else:
                    ip_address = "-"
                if bond.up:
                    status = "Up"
                else:
                    status = "Down"
                # bond-members list of interfaces.
                bond_members = ""
                if bond.bond_members != "":
                    for bond_member in bond.bond_members:
                        bond_members = bond_members + bond_member + " "
                else:
                    bond_members = "none"

                line += truncate_string(bond.name, 17)
                line += truncate_string(bond.bond_mode, 15)
                #line += truncate_string(bond.hwaddress, 21)
                line += truncate_string(ip_address, 21)
                line += truncate_string(bond.inet, 8)
                line += truncate_string(bond_members, 32)
                self.form_buttons.append(
                    self.add_widget_intelligent(npyscreen.ButtonPress, relx=4, name=line, parameters=str(bond.name),
                                                when_pressed_function=self.buttonPress))
                for vlan in network.vlans:
                    if vlan.vlan_raw_device == bond.name:
                        line = " ‣"
                        if vlan.ip != "":
                            ip_address = str(vlan.ip) + '/' + str(vlan.netmask)
                        else:
                            ip_address = "-"
                        member = ""
                        line += truncate_string(vlan.name, 15)
                        # line += truncate_string(status, 8)
                        # line += truncate_string(nic.type, 11)
                        line += truncate_string(" ", 15)
                        #line += truncate_string(" ", 21)
                        line += truncate_string(ip_address, 21)
                        line += truncate_string(vlan.inet, 8)
                        line += truncate_string(member, 21)
                        self.form_buttons.append(
                            self.add_widget_intelligent(npyscreen.ButtonPress, relx=4, name=line,
                                                        parameters=str(vlan.name),
                                                        when_pressed_function=self.buttonPress))

        line = truncate_string(" Добавить объединение интерфейсов", len(header))
        self.add_widget_intelligent(npyscreen.ButtonPress, relx=4, name=line, parameters="",
                                    when_pressed_function=self.add_bond, color=curses.COLOR_GREEN)
        self.nextrely += 1

        # перечисление портов bridge
        header = "Сетевые мосты"
        header = "[" + truncate_string(header, 81) + "]"
        self.add_widget_intelligent(npyscreen.TitleFixedText, name=" ", begin_entry_at=4, value=header, editable=False)
        if network.bridges != []:
            header = ""
            header += 'Name' + (17 - len('Name')) * ' '
            #header += 'Mode' + (15 - len('Mode')) * ' '
            #header += 'MAC' + (21 - len('MAC')) * ' '
            header += 'IP' + (21 - len('IP')) * ' '
            header += 'Inet' + (8 - len('Inet')) * ' '
            header += 'Members' + (32 - len('Members')) * ' '

            self.add_widget_intelligent(npyscreen.TitleFixedText, name=" ", begin_entry_at=4, value=header, editable=False)

            for bridge in network.bridges:
                line = ""
                if bridge.ip != "":
                    ip_address = str(bridge.ip) + '/' + str(bridge.netmask)
                else:
                    ip_address = "-"
                if bridge.up:
                    status = "Up"
                else:
                    status = "Down"
                # bond-members list of interfaces.
                bridge_ports = ""
                if bridge.bridge_ports != "":
                    for bridge_port in bridge.bridge_ports:
                        bridge_ports = bridge_ports + bridge_port + " "
                else:
                    bridge_ports = "none"

                line += truncate_string(bridge.name, 17)
                #line += truncate_string(bond.bond_mode, 15)
                #line += truncate_string(bond.hwaddress, 21)
                line += truncate_string(ip_address, 21)
                line += truncate_string(bridge.inet, 8)
                line += truncate_string(bridge_ports, 32)
                self.form_buttons.append(
                    self.add_widget_intelligent(npyscreen.ButtonPress, relx=4, name=line, parameters=str(bridge.name),
                                                when_pressed_function=self.buttonPress))

        line = truncate_string(" Добавить сетевой мост", len(header))
        self.add_widget_intelligent(npyscreen.ButtonPress, relx=4, name=line, parameters="",
                                    when_pressed_function=self.add_bridge, color=curses.COLOR_GREEN)
        self.nextrely += 1

    def buttonPress(self, parameters=None):
        self.popup_form = npyscreen.Popup()
        Message = f"Ты нажал кнопку"
        #npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False, editw=0)
        for form_button in self.form_buttons:
            Message = f"проверяем кнопку {form_button.parameters}, значение которой {form_button.value}"
            #npyscreen.notify_confirm(Message, title="Ошибка", form_color='STANDOUT', wrap=True, wide=False, editw=0)
            if form_button.value == True:
                self.nic = network.get_interface_object_by_name(form_button.parameters)
                if self.nic.type == "ethernet":
                    if self.nic.master != "":
                        message = split_string("Исключите интерфейс из объединения, для возможности его настройки", self.popup_form.max_x - 8)
                        self.popup_form.add(npyscreen.Pager, values=message)
                    else:
                        message = "Настройка IP"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                     when_pressed_function=self.configure_ip)
                        message = "Добавить VLAN"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                       when_pressed_function=self.add_vlan)
                    self.popup_form.edit()
                elif self.nic.type == "bond":
                    if False:
                        message = split_string("Какой то текст", self.popup_form.max_x - 12)
                        self.popup_form.add(npyscreen.Pager, max_width=50, values=message)
                    else:
                        message = "Настроить объединение интерфейсов"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                            when_pressed_function=self.configure_bond)
                        message = "Настройка IP"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                     when_pressed_function=self.configure_ip)
                        message = "Добавить VLAN"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                       when_pressed_function=self.add_vlan)
                        message = "Удалить объединение интерфейсов"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                       when_pressed_function=self.remove_bond)
                    self.popup_form.edit()
                elif self.nic.type == "vlan":
                    if False:
                        message = split_string("Какой то текст", self.popup_form.max_x - 12)
                        self.popup_form.add(npyscreen.Pager, max_width=50, values=message)
                    else:
                        message = "Настройка IP"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                     when_pressed_function=self.configure_ip)
                        message = "Удалить VLAN"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                       when_pressed_function=self.remove_vlan)
                    self.popup_form.edit()
                elif self.nic.type == "bridge":
                    if False:
                        message = split_string("Какой то текст", self.popup_form.max_x - 12)
                        self.popup_form.add(npyscreen.Pager, max_width=50, values=message)
                    else:
                        message = "Настроить мост"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                            when_pressed_function=self.configure_bridge)
                        message = "Настройка IP"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                     when_pressed_function=self.configure_ip)
                        message = "Удалить мост"
                        self.popup_form.add(npyscreen.ButtonPress, relx=2, name=message,
                                                                       when_pressed_function=self.remove_bridge)
                    self.popup_form.edit()

        self.exit_editing()
        self._clear_all_widgets()
        self.draw_widgets()
        self.edit()

    def configure_ip(self):
        self.configure_ip_form = ConfigureIP(self.nic.name)
        self.configure_ip_form.edit()
        self.popup_form.exit_editing()

    def add_bond(self):
        self.configure_bond_form = ConfigureBond()
        self.configure_bond_form.edit()
        self.exit_editing()
        self._clear_all_widgets()
        self.draw_widgets()
        self.edit()

    def configure_bond(self):
        self.configure_bond_form = ConfigureBond(self.nic.name)
        self.configure_bond_form.edit()
        self.popup_form.exit_editing()

    def remove_bond(self):
        path = '/sys/class/net/' + self.nic.name
        if os.path.isdir(path):
            astra.system_call(f"ip link set dev {self.nic.name} down")
            astra.system_call(f"ip link delete {self.nic.name}")
        for nic in network.nics:
            if nic.master == self.nic.name:
                nic.master = ""
                nic.bond_mode = ""
        index = network.bonds.index(network.get_interface_object_by_name(self.nic.name))
        del network.bonds[index]
        self.popup_form.exit_editing()

    def add_bridge(self):
        self.configure_bridge_form = ConfigureBridge()
        self.configure_bridge_form.edit()
        self.exit_editing()
        self._clear_all_widgets()
        self.draw_widgets()
        self.edit()

    def configure_bridge(self):
        self.configure_bridge_form = ConfigureBridge(self.nic.name)
        self.configure_bridge_form.edit()
        self.popup_form.exit_editing()

    def remove_bridge(self):
        path = '/sys/class/net/' + self.nic.name
        if os.path.isdir(path):
            astra.system_call(f"ip link set dev {self.nic.name} down")
            astra.system_call(f"ip link delete {self.nic.name}")
        for nic in network.nics:
            if nic.master == self.nic.name:
                nic.master = ""
        for bond in network.bonds:
            if bond.master == self.nic.name:
                bond.master = ""
        for vlan in network.vlans:
            if vlan.master == self.nic.name:
                vlan.master = ""
        index = network.bridges.index(network.get_interface_object_by_name(self.nic.name))
        del network.bridges[index]
        self.popup_form.exit_editing()

    def add_vlan(self):
        self.add_vlan_form = ConfigureVlan(self.nic.name)
        self.add_vlan_form.edit()
        self.popup_form.exit_editing()

    def remove_vlan(self):
        path = '/sys/class/net/' + self.nic.name
        if os.path.isdir(path):
            astra.system_call(f"ip link set dev {self.nic.name} down")
            astra.system_call(f"ip link delete {self.nic.name}")
        index = network.vlans.index(network.get_interface_object_by_name(self.nic.name))
        network.get_interface_object_by_name(network.vlans[index].vlan_raw_device).vlans_count =- 1
        del network.vlans[index]
        self.popup_form.exit_editing()

    def adjust_widgets(self):
        self.display()

    def on_ok(self):
        with open("/etc/network/interfaces", "w") as interfaces_file:
            print("# This file was generated by AstraConfig utility", file=interfaces_file)
            print("", file=interfaces_file)
            print("# This file describes the network interfaces available on your system", file=interfaces_file)
            print("# and how to activate them. For more information, see interfaces(5).", file=interfaces_file)
            print("", file=interfaces_file)
            print("source /etc/network/interfaces.d/*", file=interfaces_file)
            print("", file=interfaces_file)
            print("# The loopback network interface", file=interfaces_file)
            print("", file=interfaces_file)
            print("auto lo", file=interfaces_file)
            print("iface lo inet loopback", file=interfaces_file)
            print("", file=interfaces_file)
            for nic in network.nics:
                print(nic.get_init_script(all=False), file=interfaces_file)
            for bond in network.bonds:
                print(bond.get_init_script(all=False), file=interfaces_file)
            for vlan in network.vlans:
                print(vlan.get_init_script(all=False), file=interfaces_file)
            for bridge in network.bridges:
                print(bridge.get_init_script(all=False), file=interfaces_file)
        system_call(f"sudo systemctl stop NetworkManager")
        system_call(f"sudo systemctl --now mask NetworkManager")
        system_call(f"sudo apt -y remove network-manager-gnome")
        system_call(f"sudo mv /etc/xdg/autostart/nm-applet.desktop /etc/xdg/autosart/nm-applet.desktop.disabled")
        system_call(f"systemctl restart networking")
        self.fqdn = os.uname().nodename
        self.hostname=self.fqdn.split(".")[0]
        self.domainname=self.fqdn[self.fqdn.index(self.hostname)+len(self.hostname)+1:]
        astra.update_hosts(self.hostname, self.domainname, network.main_ip)


    def on_cancel(self):
        pass
